package controller

import (
	"api_interface/entity"
	"api_interface/service"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

/*
收到提问信息
*/
func GetMessage() gin.HandlerFunc {
	return func(c *gin.Context) {
		id := c.DefaultQuery("uid", "")
		typ := c.DefaultQuery("message_type", "")
		uid, _ := strconv.Atoi(id)
		message_type, _ := strconv.Atoi(typ)
		//输出json结果给调用方
		messages, err := service.GetQuestionMessage(uid, message_type)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "fail to get messages",
				"data": nil,
			})
			return
		}

		type MesData struct {
			Total    int                  //`json:"total"`
			Messages []entity.MessageInfo //`json:"boxes"`
		}
		data := MesData{
			Total:    len(*messages),
			Messages: *messages,
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "success",
			"data": data,
		})
	}
}

/*
加入信息
*/

func Join_msg() gin.HandlerFunc {
	return func(c *gin.Context) {

	}
}

func Reply_msg() gin.HandlerFunc {
	return func(c *gin.Context) {

	}
}

/*
关注信息
*/
func Concern_msg() gin.HandlerFunc {
	return func(c *gin.Context) {

	}
}

//存储消息

func SaveMessages() gin.HandlerFunc {
	return func(c *gin.Context) {
		var message entity.MessageInfo
		if err := c.BindJSON(&message); err != nil { //将body里的JSON格式数据解构到message里
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "error to get json body",
				"data": nil,
			})
			return
		}
		currentTime := time.Now()
		timeString := currentTime.Format("2006-01-02 15:04:05") //定义时间存储样式
		message.Tim = timeString
		err := service.SaveMessages(&message) //调用service层函数，将message传给函数用于创建message
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "error to save message",
				"data": nil,
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{ //无error，返回success
			"code": 0,
			"msg":  "success",
			"data": nil,
		})
	}
}

//设置消息为已读

func SetMessageRead() gin.HandlerFunc {
	return func(c *gin.Context) {
		mid := c.DefaultQuery("id", "")
		id, _ := strconv.Atoi(mid)
		err := service.SetMessageRead(id)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "fail to set message read",
				"data": nil,
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "success",
			"data": nil,
		})
	}
}

//删除某人的已读消息

func DeleteMessages() gin.HandlerFunc {
	return func(c *gin.Context) {
		rid := c.DefaultQuery("id", "")
		id, _ := strconv.Atoi(rid)
		err := service.DeleteMessages(id)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "fail to delete messages",
				"data": nil,
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "success",
			"data": nil,
		})
	}
}
